<!-- template.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Ajax Search</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="text" id="search-input" placeholder="Enter category">
    <button id="search-btn">Search</button>

    <table id="results-table" style="margin-top: 20px; display: none;">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <script>
    $(document).ready(function(){
        $('#search-btn').click(function(){
            const category = $('#search-input').val();

            $.ajax({
                url: '{% url "product_search" %}',
                type: 'GET',
                data: {
                    'category': category
                },
                dataType: 'json',
                success: function(data) {
                    $('#results-table').show();
                    const tbody = $('#results-table tbody').empty();

                    if(data.length === 0) {
                        tbody.append('<tr><td colspan="3">No products found</td></tr>');
                    } else {
                        $.each(data, function(i, item){
                            tbody.append(`
                                <tr>
                                    <td>${item.id}</td>
                                    <td>${item.name}</td>
                                    <td>$${item.price}</td>
                                </tr>
                            `);
                        });
                    }
                },
                error: function(xhr) {
                    console.error('Error:', xhr.responseText);
                    alert('Error fetching data');
                }
            });
        });
    });
    </script>
</body>
</html>